/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sasp_messages;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import sasp_udp.UDPListener;
import sasp_udp.UDPMessage;
import sasp_udp.UDPTransceiver;

/**
 *
 * @author mauriello
 */
public class MessageHandler implements UDPListener {
    public enum Commands
    {
        PING, REQ_TBL, REQ_SN, REQ_DATA, UPD_DATA, UPD_KEY, FIND_SN, 
        PRO_NODE, NEW_NODE, JOIN_REQUEST, SESSION_KEY, QUIT, RESET, NOVALUE;

        public static Commands toCommand(String str)
        {
            try {
                return valueOf(str);
            } 
            catch (Exception ex) {
                return NOVALUE;
            }
        }   
    }

    public enum Replies
    {
        ACK, NOVALUE;

        public static Replies toReply(String str)
        {
            try {
                return valueOf(str);
            }
            catch (Exception ex) {
                return NOVALUE;
            }
        }
    }

    private UDPTransceiver udpTransceiver;

    public MessageHandler( UDPTransceiver _t ) {
        udpTransceiver = _t;
    }

    public void sendPing( int _d ) {
        PINGCommand command = new PINGCommand(1,2,3); /* TODO: Implement Node Table and Message Count */
        udpTransceiver.transmitUdpMessage("127.0.0.1", 12345, command.toString());
    }

    public void handleMessage(UDPMessage _rcvMessage) {
        try {
            JSONObject inMessage = new JSONObject(_rcvMessage.getTheMessage());
            if( inMessage.has("SASPv1Command")) {
                switch(Commands.toCommand(inMessage.getString("SASPv1Command"))) {
                    case PING:
                        PINGCommand cmd = new PINGCommand(_rcvMessage.getTheMessage());
                        udpTransceiver.transmitUdpMessage(_rcvMessage.getIpAddress(), 12344, cmd.execute().toString());
                        break;
                    default:
                        System.out.println("MES - Unsupported SASP Command = " + inMessage.getString("SASPv1Command"));
                        break;
                }
            } else if( inMessage.has("SASPv1Reply")) {
                switch(Replies.toReply(inMessage.getString("SASPv1Reply"))) {
                    case ACK:
                        ACKReply rep = new ACKReply(_rcvMessage.getTheMessage());
                        
                        break;
                    default:
                        System.out.println("MES - Unsupported SASP Reply - " + inMessage.getString("SASPv1Reply"));
                        break;
                }
            }
        } catch (JSONException ex) {
            Logger.getLogger(MessageHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
